import axios from 'axios'
import { notification, Modal } from 'antd';
const { confirm } = Modal;
const loginExpire = ()=>{
    Modal.destroyAll()
    confirm({
            title: '系统提示',
            content: '未登录或登录状态已过期',
            autoFocusButton:null,
            okCancel:false,
            onOk() {
                localStorage.removeItem('permissions')
                localStorage.removeItem('token')
                window.open('/login','_self')
            },
            onCancel() {

            },
        }
    )
}
// create an axios instance
const request = axios.create({
    //开发环境用代理.打包用固定url
    timeout: 10*1000, //request timeout
    baseURL:'/services/admin'
})
// request interceptor
request.interceptors.request.use(
    config => {
        config.headers['X-Auth-Token'] = window.localStorage.getItem('token') || ''
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
// response interceptor
request.interceptors.response.use(
   
    response => {
        if (response.headers['x-auth-token']) {
            window.localStorage.setItem('token', response.headers['x-auth-token'])
        }
        const res = response.data
        const {code=200,msg} = res
        if(code !==200){
            notification.error({
                description: msg||'',
                message: `请求错误: ${code}`,
            });
        }
        return res
    },
    error => {
        let { message='请求异常' } = error;
        console.log("error",error);
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        if(error.response && error.response.status === 401){
            Modal.destroyAll();
            loginExpire();
        }else{
            notification.error({
                message: message
            });
        }
   
        return Promise.reject(error)
    }
)

export default request